//
//  HYUnit.m
//  DaJiaZhuan
//
//  Created by Bibo on 15/1/15.
//  Copyright (c) 2015年 Bibo. All rights reserved.
//

#import "HYUnit.h"
#import "iOSMD5.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

@implementation HYUnit

// 是否为手机号
+ (BOOL)isPhoneNumber: (NSString *)mobileNum {
    mobileNum = [mobileNum stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    return (mobileNum.length == 11);
    
    //    if (mobileNum.length != 11)
    //    {
    //        return NO;
    //    }
    //    /**
    //     * 手机号码:
    //     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
    //     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
    //     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
    //     * 电信号段: 133,153,180,181,189,177,1700
    //     */
    //    NSString *MOBILE = @"^1((3[0-9]|4[57]|5[0-35-9]|7[0-9]|8[0-9])\\d{8}$)";
    //    /**
    //     * 中国移动：China Mobile
    //     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
    //     */
    //    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    //    /**
    //     * 中国联通：China Unicom
    //     * 130,131,132,155,156,185,186,145,176,1709
    //     */
    //    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    //    /**
    //     * 中国电信：China Telecom
    //     * 133,153,180,181,189,177,1700
    //     */
    //    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
    //
    //
    //    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    //    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    //    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    //    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    //
    //    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
    //        || ([regextestcm evaluateWithObject:mobileNum] == YES)
    //        || ([regextestct evaluateWithObject:mobileNum] == YES)
    //        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    //    {
    //        return YES;
    //    }
    //    else
    //    {
    //        return NO;
    //    }
}

//字符串加密
+ (NSString *)hashed_string:(NSString *)input
{
    NSString *strAddSalt = [NSString stringWithFormat:@"%@%@",input,@"HZMetro_DtDream&(SJDJ^EHDJOO#KSDISDJF#*(OSJsisj82*AS"];
    
    const char *cstr = [strAddSalt cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:strAddSalt.length];
    
    uint8_t digest[CC_SHA512_DIGEST_LENGTH];
    //加密
    CC_SHA512(data.bytes, (CC_LONG)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
    {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}
/**
 *号码格式， 3 4 4
 */
+ (NSString *) ReturnNumFormater: (NSString *)string {
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (string.length > 13) {
        string = [string substringToIndex:12];
    }
    NSMutableString *returnString = [NSMutableString stringWithString:string];
    if (string.length >= 3) {
        [returnString insertString:@" " atIndex:3];
    }
    if (string.length >= 7) {
        [returnString insertString:@" " atIndex:8];
    }
    return returnString;
}

/**
 *随机返回某个区间范围内的值
 */
+ (float) randomBetweenSmaller:(float)smallerNumber AndLarger:(float)largerNumber AndPrecision:(int) precision
{
    //设置精确的位数
    precision = precision * 100;
    //先取得他们之间的差值
    float subtraction = largerNumber - smallerNumber;
    //取绝对值
    subtraction = ABS(subtraction);
    //乘以精度的位数
    subtraction *= precision;
    //在差值间随机
    float randomNumber = arc4random() % ((int)subtraction+1);
    //随机的结果除以精度的位数
    randomNumber /= precision;
    //将随机的值加到较小的值上
    float result = MIN(smallerNumber, largerNumber) + randomNumber;
    
    //返回结果
    return result;
}
/**
 *处理非法字符：去除左右空格
 */
+ (NSString *) returnRightFormerString : (NSString *)inputString{
    
    NSString *outPutString = inputString;
    
    //去除左右空字符串
    outPutString = [outPutString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    //去除符号表情，等非法字符
    
    return outPutString;
}
/**
 *一个字符串中对某个字符 颜色 大小设置
 */
+ (void) designLabel :(UILabel *)label AndString: (NSString *)string AndValue:(NSRange) range{
    
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:string];
    [noteStr addAttribute:NSFontAttributeName
                    value:[UIFont systemFontOfSize:12]
                    range:range];
    
    [label setAttributedText:noteStr] ;
}

+ (NSString *) returnMilesFromMeters: (int)targetDistance {
    NSString *distanceString;
    if (targetDistance >= 1000) {
        double distanceMile = targetDistance;
        distanceMile = distanceMile / 1000;
        distanceString = [NSString stringWithFormat:@"%.1f 公里",distanceMile];
    } else {
        distanceString = [NSString stringWithFormat:@"%d 米",targetDistance];
    }
    
    return distanceString;
}

+ (NSString *) returnRightTimeFormer: (NSString *)time{
    //想要设置自己想要的格式，可以用nsdateformatter这个类，这里是初始化
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    //指定输出的格式   这里格式必须是和上面定义字符串的格式相同，否则输出空
    [formatter setDateFormat:@"HH:mm:ss"];
    NSDate  *newdate=[formatter dateFromString:time];
    
    // 把时间转换成字符串，把Date对象转换成String对象  用stringFromDate方法
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];
    [formatter2 setDateFormat:@"HH:mm"];
    NSString *stringTime = [formatter2 stringFromDate:newdate];
//    NSLog(@"%@",stringTime);
    return stringTime;
}

+ (NSString *)returnRightTimeFormer:(NSString *)formatter AndTimeString:(NSString *)time {

    NSTimeInterval dateDouble = [time doubleValue] / 1000;
    //获取此字符串日期信息
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:dateDouble];
    
    //日期格式
    NSString *dateFMT = formatter;
    
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
    [formatter2 setDateFormat:dateFMT];
    NSString *createString = [formatter2 stringFromDate:date];
    
    return createString;
}

/**
 * 根据秒数 返回:XX小时XX分钟
 */
+ (NSString *)changeSecondsToMinutes:(int)seconds {
    
    
    int nextTimeSeconds = seconds;
    int nextTimeHours = nextTimeSeconds / 3600;
    int nextTimeMintes = (nextTimeSeconds / 60) - (nextTimeHours * 60);
    NSString *timeString = @"";
    /*  显示到达时间格式   */
    if (nextTimeHours == 0) {
        //不显示小时
        if (nextTimeMintes == 0) {
            //不显示小时，不显示分钟
            timeString = [NSString stringWithFormat:@"即将"];    //一分钟内到达
        } else {
            //不显示小时，显示分钟
            timeString = [NSString stringWithFormat:@"%d分钟",nextTimeMintes];//N分钟内到达
        }
    } else {
        //显示小时，显示分钟
        timeString = [NSString stringWithFormat:@"%d小时%d分钟",nextTimeHours,nextTimeMintes];    //N小时N分钟内到达
    }

    
    return timeString;
}


/**
 * UITextField实现左侧空出一定的边距
 */
+ (UITextField *)setTextFieldLeftPadding:(UITextField *)textField forWidth:(CGFloat)leftWidth
{
    CGRect frame = textField.frame;
    frame.size.width = leftWidth;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView = leftview;
    
    return textField;
}

/**
 *  Unicode转成汉字
 *
 *  @param aUnicodeString
 *
 *  @return 汉字
 */
/*
 有修改，不知会不会造成不兼容
 /Users/rdic/Desktop/zzq_Work/HZBus/Code-PreRelease/PublicTransport/iOS/HZBus/Library/UI+Category/UIButton+CountDown/HYUnit.m:127:56: 'propertyListFromData:mutabilityOption:format:errorDescription:' is deprecated: first deprecated in iOS 8.0 - Use propertyListWithData:options:format:error: instead.
 */
+ (NSString*)replaceUnicode:(NSString*)aUnicodeString
{
    
    NSString *tempStr1 = [aUnicodeString stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
//    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
//                                                           mutabilityOption:NSPropertyListImmutable
//                                                                     format:NULL
//                                                           errorDescription:NULL];
    NSString *returnStr = [NSPropertyListSerialization propertyListWithData:tempData
                                                                    options:NSPropertyListImmutable
                                                                     format:NULL
                                                                      error:NULL];
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

/**
 *  获取验证码
 *
 *  @return 验证码
 */
+ (NSString *)getVerifCode
{
    NSString *strCode = [NSString stringWithFormat:@"%d%d%d%d",arc4random()%5 ,arc4random()%5,arc4random()%5,arc4random()%5];
    return strCode;
}

/**
 *  计算文本高度
 *
 *  @param value    文本内容
 *  @param fontSize 字体大小
 *  @param width    文本框宽度
 *
 *  @return 高度
 */
+ (float)heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
    UITextView *detailTextView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, width, 0)];
    detailTextView.font = [UIFont systemFontOfSize:fontSize];
    detailTextView.text = value;
    CGSize deSize = [detailTextView sizeThatFits:CGSizeMake(width,CGFLOAT_MAX)];
    return deSize.height;
}

/**
 *  计算文本长度
 *
 *  @param value    文本内容
 *  @param fontSize 字体大小
 *  @param width    文本框宽度
 *
 *  @return 长度
 */
+ (float)widthForString:(NSString *)value fontSize:(float)fontSize
{
    UITextView *detailTextView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, CGSizeZero.width, 0)];
    detailTextView.font = [UIFont systemFontOfSize:fontSize];
    detailTextView.text = value;
    CGSize deSize = [detailTextView sizeThatFits:CGSizeZero];
    return deSize.width;
}

/**
 *  获取当前版本号
 *
 *  @return 版本号
 */
+ (NSString *)getCurrentVersion
{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDic objectForKey:@"CFBundleVersion"];
    
    return appVersion;
}


/**
 *  获取城市ID
 *
 *  @param strRegionID 地区IDparentid
 */
+ (NSString *)getCityID:(NSString *)strRegionID
{
    NSString *strCityPath = [[NSBundle mainBundle] pathForResource:@"region" ofType:@"plist"]; ;
    NSMutableArray *mutarrCity = [[NSMutableArray alloc] initWithContentsOfFile:strCityPath];
    
    NSString *strCityID;
    
    for (int i = 0; i < mutarrCity.count; i++)
    {
        NSDictionary *dicItem = mutarrCity[i];
        if ([[dicItem objectForKey:@"regionid"] isEqualToString:strRegionID])
        {
            strCityID = [dicItem objectForKey:@"parentid"];
            
            return strCityID;
        }
    }
    
    return strCityID;
}

/**
 *  过滤html标签
 *
 *  @param html
 *
 *  @return
 */
+ (NSString *)removeHTML:(NSString *)html
{
    html = [html stringByReplacingOccurrencesOfString:@"<(.[^>]*)>" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"([\r\n])[\\s]+" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"../" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"\r\n" withString:@"\\n"];
    html = [html stringByReplacingOccurrencesOfString:@"<br />" withString:@"\\n"];
    html = [html stringByReplacingOccurrencesOfString:@"<br>" withString:@"\\n"];
    html = [html stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
    html = [html stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"<span>" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"</span>" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"\u00a0" withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
    
    return html;
}

/**
 *  unicode转汉字
 *
 *  @param unicodeStr
 *
 *  @return
 */
/*
 有修改，不知会不会造成不兼容
 /Users/rdic/Desktop/zzq_Work/HZBus/Code-PreRelease/PublicTransport/iOS/HZBus/Library/UI+Category/UIButton+CountDown/HYUnit.m:271:56: 'propertyListFromData:mutabilityOption:format:errorDescription:' is deprecated: first deprecated in iOS 8.0 - Use propertyListWithData:options:format:error: instead.
 */
- (NSString *)replaceUnicode:(NSString *)unicodeStr
{
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
//    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
//                                                           mutabilityOption:NSPropertyListImmutable
//                                                                     format:NULL
//                                                           errorDescription:NULL];
    NSString *returnStr = [NSPropertyListSerialization propertyListWithData:tempData
                                                                    options:NSPropertyListImmutable
                                                                     format:NULL
                                                                      error:NULL];
    
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

/*! @brief 计算文本高度
 *
 *@param text 文本内容
 *@param textWith 文本框宽度
 *@result float 返回文本高度
 */
+ (float)heightForText:(NSString *)text fontSize:(float)fontSize textWith:(float)textWith
{
    CGSize constraint = CGSizeMake(textWith, 20000.0f);
    
    NSDictionary * attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:fontSize] forKey:NSFontAttributeName];
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:attributes];
    CGRect rect = [attributedText boundingRectWithSize:constraint
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    CGSize size = rect.size;
    return size.height;
}


+ (CGSize)sizeForText:(NSString *)text fontSize:(UIFont *)font textWith:(float)textWith
{
    CGSize constraint = CGSizeMake(textWith, 20000.0f);
    
    NSDictionary * attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:attributes];
    CGRect rect = [attributedText boundingRectWithSize:constraint
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    CGSize size = rect.size;
    return size;
}


/**
 *  拼接通讯URL
 *
 *  @param strUrl   通讯URL
 *  @param strOp    方法
 *  @param arrKey   参数名
 *  @param arrValue 参数值
 *
 *  @return URL
 */
+ (NSString *)StrpageUrlByURL:(NSString *)strUrl Op:(NSString *)strOp Key:(NSArray *)arrKey Value:(NSArray *)arrValue
{
    NSString *str = [NSString stringWithFormat:@"%@%@",strUrl,strOp];
    
    for (int i = 0; i < arrKey.count; i ++)
    {
        if (i == 0)
        {
            str = [str stringByAppendingFormat:@"%@=%@",arrKey[i],arrValue[i]];
        }
        else
        {
            str = [str stringByAppendingFormat:@"&%@=%@",arrKey[i],arrValue[i]];
        }
        
    }
    
    str = [str stringByReplacingOccurrencesOfString:@"\r\n" withString:@"<br>"];
    str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@"<br>"];
    str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@"<br>"];
    
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    return str;
}

/*! @brief 获取此app版本号
 */
+ (NSString *)getAppVersion
{
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *strAppVersion = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"];
    return strAppVersion;
}

/*! @brief 获取系统语言
 */
+ (NSString *)getSysLanguage
{
    NSArray *languageArray = [NSLocale preferredLanguages];
    NSString *language = [languageArray objectAtIndex:0];
    
    return language;
}

/**
 *  信息按拼音A-Z排序
 *
 *  @param arrAllData      排序数据
 *  @param strShortPYKey   排序依据拼音的Key值
 *
 *  @return URL
 */
+ (NSDictionary *)divideDictionaryInMutableArray:(NSArray *)arrAllData shortPYKey:(NSString *)strShortPYKey
{
    //建立#组
    NSMutableArray *marrTitleFrist = [NSMutableArray new];
    for (int i = 0; i < arrAllData.count; i++)
    {
        NSDictionary *dic = arrAllData[i];
        if ([dic[strShortPYKey] length]==0)
        {
            [marrTitleFrist addObject:dic];
        }
        else
        {
            char cFrist = [dic[strShortPYKey] characterAtIndex:0];
            if (cFrist<'A'||cFrist>'Z')
            {
                [marrTitleFrist addObject:dic];
            }
            else
            {
                break;
            }
        }
    }
    
    NSMutableArray *marrTitle = [[NSMutableArray alloc]init];
    NSMutableArray *marrTempTitle = [[NSMutableArray alloc]init];
    char cLetter = 'A';
    NSString *strLetter = [NSString stringWithFormat:@"%c",cLetter];
    //根据首字母分组
    for (NSUInteger i = marrTitleFrist.count ; i < arrAllData.count;i++)
    {
        NSDictionary *dic = arrAllData[i];
        if ([dic[strShortPYKey] hasPrefix:strLetter])
        {
            [marrTempTitle addObject:dic];
        }
        else
        {
            cLetter = cLetter+1;
            strLetter = [NSString stringWithFormat:@"%c",cLetter];
            if (marrTempTitle.count != 0)
            {
                [marrTitle addObject:marrTempTitle];
                marrTempTitle = [[NSMutableArray alloc]init];
            }
            i--;
        }
    }
    
    //添加最后一组
    if (marrTempTitle.count > 0)
    {
        [marrTitle addObject:marrTempTitle];
        //marrTempTitle = [[NSMutableArray alloc]init];
    }
    
    //建立索引数据
    NSMutableArray *marrSectionTitle = [[NSMutableArray alloc]init];
    for (int i = 0; i < marrTitle.count;i++)
    {
        NSString *strSectionTitle = [[marrTitle[i][0] objectForKey:strShortPYKey]substringToIndex:1];
        [marrSectionTitle addObject:strSectionTitle];
    }
    if (marrTitleFrist.count>0)
    {
        [marrSectionTitle insertObject:@"#" atIndex:0];
        [marrTitle insertObject:marrTitleFrist atIndex:0];
    }
    
    return @{@"marrIndexTitle":marrSectionTitle,@"marrDicData":marrTitle};
}

/**
 *  字典转Json
 *
 *  @param dic 要转换的字典
 *
 *  @return Json格式字符串
 */
+ (NSString *)jsonFromDictionary:(NSDictionary *)dic
{
    if ([NSJSONSerialization isValidJSONObject:dic])
    {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSLog(@"不是JSON格式");
    return @"";
}

+ (NSString *)jsonFromObj:(id)obj
{
    if ([NSJSONSerialization isValidJSONObject:obj])
    {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:nil];
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSLog(@"无法转换");
    return @"";
}

/**
 *  项目英文名+接口名称+日期(yyyy-MM-dd)+请求体 生成签名
 *
 *  @param strOp   接口名称
 *  @param strbody 请求体（Json格式）
 *
 *  @return 签名
 */
//test
//#define G_WEBSERVICE_PROJECTNAME
+ (NSString *)MD5SignatureFromProjectNameAndOP:(NSString *)strOp dateAndJsonBody:(NSString *)strbody
{
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [formatter stringFromDate:[NSDate date]];
    
    NSString *strName = @"";
#ifdef G_WEBSERVICE_PROJECTNAME
    strName = G_WEBSERVICE_PROJECTNAME;
#endif
    NSString *str = [NSString stringWithFormat:@"%@%@%@%@",strName,strOp,strDate,strbody];

    return [iOSMD5 md5:str];
}

//截取到字符串中最后一个 "tagString" 前
+ (NSString *)getSubStringToTag:(NSString *)tagString ForOriginString:(NSString *)originString{
    NSRange range = [originString rangeOfString:tagString options:NSBackwardsSearch];
    NSString *returnString = nil;
    if (range.length > 0) {
        returnString = [originString substringToIndex:range.location];
    }
    return returnString;
}

@end
